package pb

import (
	"strings"

	"github.com/xelabs/go-mysqlstack/sqlparser/depends/query"
	"github.com/xelabs/go-mysqlstack/sqlparser/depends/sqltypes"
)

func (p *Msg) ToResult() *sqltypes.Result {
	res := &sqltypes.Result{
		RowsAffected: p.RowsAffected,
		InsertID:     p.InsertID,
	}

	res.Fields = make([]*query.Field, len(p.Fields))
	for i, field := range p.Fields {
		res.Fields[i] = &query.Field{
			Name: field.Name,
			Type: query.Type(field.Type),
		}
	}

	res.Rows = make([][]sqltypes.Value, len(p.Rows))

	for rowIndex, row := range p.Rows {
		values := make([]sqltypes.Value, len(p.Fields))

		for fieldIndex, field := range p.Fields {
			if len(row.Data[fieldIndex]) > 0 {
				values[fieldIndex] = sqltypes.MakeTrusted(query.Type(field.Type), row.Data[fieldIndex])
			}
		}

		res.Rows[rowIndex] = values
	}

	return res
}

func (p *Msg) IsQuery() bool {
	if sql := strings.ToUpper(p.Sql); strings.Contains(sql, "UPDATE") ||
		strings.Contains(sql, "INSERT") ||
		strings.Contains(sql, "DELETE") ||
		strings.Contains(sql, "TRUNCATE") {
		return false
	}

	return true
}
